import { AnimationClip, Sprite, SpriteFrame, animation } from "cc"
import { StateMachine } from "./StateMachine"
import ResManager from "../../../runtime/ResManager"

export class State {

    /** 序列帧动画初始化完成 */
    initTag = false
    clip: AnimationClip
    constructor(
        private fsm: StateMachine,
        private entityType: any,
        private type: number,
        /** 播放模式 */
        private wrapMode: AnimationClip.WrapMode = AnimationClip.WrapMode.Loop,
        /** 播放速度 */
        private speed = 8
    ) {

        const track = new animation.ObjectTrack()
        track.path = new animation.TrackPath().toHierarchy('body').toComponent(Sprite).toProperty('spriteFrame')
        ResManager.Ins.getAniSpriteFrames(this.entityType, this.type).then((spriteFrames) => {
            const frames = spriteFrames ? this.getSpriteFrames(spriteFrames) : []
            track.channel.curve.assignSorted(frames)
            this.clip = new AnimationClip()
            this.clip.name = this.type.toString()
            this.clip.duration = frames.length
            this.clip.wrapMode = this.wrapMode
            this.clip.addTrack(track)
            this.clip.speed = this.speed

            if (
                this.type.toString() == 'idle' ||
                !this.fsm.animationComponent?.defaultClip
            ) {
                this.fsm.animationComponent.defaultClip = this.clip
            }

            this.fsm.animationComponent.play()
            this.initTag = true
        })

    }

    run() {
        if (
            this.fsm.animationComponent?.defaultClip?.name == this.type.toString()
            || !this.initTag
        ) {
            return
        }
        this.fsm.animationComponent.defaultClip = this.clip
        this.fsm.animationComponent.play()
    }

    /** 获取帧动画图 */
    getSpriteFrames(arg: SpriteFrame[]) {
        const spriteFrames = arg

        spriteFrames.sort((a, b) => {
            const aStr = a.name.split('_')
            const bStr = b.name.split('_')
            if (aStr.length > 1 && bStr.length > 1) {
                return Number(aStr[1]) - Number(bStr[1])
            } else if (aStr.length == 1 && bStr.length == 1) {
                return Number(aStr[0]) - Number(bStr[0])
            }
            return 0
        })

        let index = 0
        const frames: [number, SpriteFrame][] = []

        spriteFrames.map((v, i) => {
            frames.push([index++, v])
        })

        return frames
    }
}